#include "packet_queue.h"
#include <iostream>

/**
 *
 */
PacketQueue::PacketQueue()
	: firstPkt(0),
	  lastPkt(0),
	  nbPackets_(0),
	  size_(0),
	  abortRequest_(0)
{}

PacketQueue::~PacketQueue() {}

/**
 *
 */
void PacketQueue::stopWaiting() {
	Lock l(mutex_);
	this->abortRequest_ = 1;
	cond_.notify();
}

/**
 *
 */
int PacketQueue::put(AVPacket *pkt) {
	Lock l(mutex_);

	AVPacketList *pkt1;
	if (av_dup_packet(pkt) < 0)
		return -1;

	pkt1 = (AVPacketList*) av_malloc(sizeof(AVPacketList));
	if (!pkt1)
		return -1;
	pkt1->pkt = *pkt;
	pkt1->next = NULL;

	if (!this->lastPkt)
		this->firstPkt = pkt1;
	else
		this->lastPkt->next = pkt1;

	this->lastPkt = pkt1;
	this->nbPackets_++;
	this->size_ += pkt1->pkt.size;

	cond_.notify();
	return 0;
}

/**
 *
 */
int PacketQueue::get(AVPacket *pkt) {
	Lock l(mutex_);

	AVPacketList *pkt1;
	int ret;

	for (;;) {
		if (this->abortRequest_) {
			ret = -1;
			break;
		}

		pkt1 = this->firstPkt;
		if (pkt1) {
			this->firstPkt = pkt1->next;
			if (!this->firstPkt)
				this->lastPkt = NULL;
			this->nbPackets_--;
			this->size_ -= pkt1->pkt.size;
			*pkt = pkt1->pkt;
			av_free(pkt1);
			ret = 1;
			break;
		} else {
			cond_.wait(mutex_);
		}
	}

	return ret;
}
